﻿using System;
using System.Collections.ObjectModel;
using System.IdentityModel.Tokens;
using SecurityTokenServiceNS;
using System.IdentityModel.Claims;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.ServiceModel;

namespace IssuedClaimsAddIns
{
	public class IssuedClaimsModuleMappings : IIssuedClaimsProcessor
	{
		public void GetIssuedClaims(RST rst, Collection<Claim> claims)
		{
			ReadOnlyCollection<ClaimSet> claimSets = OperationContext.Current.ServiceSecurityContext.AuthorizationContext.ClaimSets;

			foreach (ClaimSet claimSet in claimSets)
				foreach (Claim claim in claimSet)
					foreach (ClaimMapping cm in StsConfiguration.Current.ClaimMappings.GetMappingByEndpoint(rst.AppliesTo))
						foreach (ClaimTypeRequirement ctr in rst.Claims)
							ProcessClaim(claims, claim, cm, ctr);
		}

		private void ProcessClaim(Collection<Claim> claims,
			Claim claim, ClaimMapping cm, ClaimTypeRequirement ctr)
		{
			if (cm.ToType == ""
				&& string.Compare(cm.FromType, claim.ClaimType, true) == 0
				&& string.Compare(cm.FromType, ctr.ClaimType, true) == 0)
			{
				claims.Add(claim);
			}
			else if (string.Compare(cm.FromType, claim.ClaimType, true) == 0
				&& string.Compare(cm.ToType, ctr.ClaimType, true) == 0)
			{
				claims.Add(TransformClaim(claim, cm.ToType));
			}
		}

		private Claim TransformClaim(Claim claim, string toType)
		{
			//Get a new claim using the supplied claim, can be through database, Active Directory, etc.
			return new Claim(ClaimTypes.Email, "jhfigueiredo@netvisao.pt", Rights.PossessProperty);
		}
	}
}
